package timing.ukulele.third.handler;

import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;
import timing.ukulele.common.util.LocalDateTimeUtils;
import timing.ukulele.data.third.view.common.SysThirdPartyUserVO;
import timing.ukulele.third.persistent.common.SysThirdPartyUser;
import timing.ukulele.third.persistent.weixin.WxAutoReply;
import timing.ukulele.third.persistent.weixin.WxUser;
import timing.ukulele.third.constant.WxConstant;
import timing.ukulele.third.persistent.weixin.WxApp;
import timing.ukulele.third.service.common.SysThirdPartyUserService;
import timing.ukulele.third.service.weixin.WxAppService;
import timing.ukulele.third.service.weixin.WxAutoReplyService;
import timing.ukulele.third.service.weixin.WxMsgService;
import timing.ukulele.third.service.weixin.WxUserService;
import java.util.List;
import java.util.Map;

/**
 * 用户关注
 */
@Slf4j
@Component
@AllArgsConstructor
public class SubscribeHandler extends AbstractHandler {

    private final WxAppService wxAppService;

    private final SysThirdPartyUserService sysThirdPartyUserService;

    private final WxUserService wxUserService;

    private final WxAutoReplyService wxAutoReplyService;

    private final WxMsgService wxMsgService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
                                    WxMpService weixinService, WxSessionManager sessionManager) throws WxErrorException {
        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        // 获取微信用户基本信息
        WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
        if(userWxInfo != null) {
            // 获取微信公众号
            WxApp wxApp = wxAppService.findEntityByWexinSign(wxMessage.getToUser());

            if(wxApp != null) {
                // 处理系统第三方用户，如果不存在那么新增
                Integer platSource = WxConstant.WX_APP_TYPE_1.equals(wxApp.getAppType()) ? 1 : 2;
                SysThirdPartyUserVO sysThirdPartyUser = sysThirdPartyUserService.getByPlatSourceAndId(platSource, wxApp.getAppId(), userWxInfo.getOpenId());
                if(sysThirdPartyUser == null) {
                    SysThirdPartyUser insert = new SysThirdPartyUser();
                    insert.setPlatSource(platSource);
                    insert.setAppId(wxApp.getAppId());
                    insert.setPlatId(userWxInfo.getOpenId());
                    insert.setUnionId(userWxInfo.getUnionId());
                    sysThirdPartyUserService.save(insert);
                }

                // 处理微信用户
                WxUser wxUser = wxUserService.getByOpenId(wxApp.getAppId(), userWxInfo.getOpenId());
                // 第一次关注
                if(wxUser == null) {
                    wxUser = new WxUser();
                    wxUser.setSubscribeNum(1);
                    setWxUserValue(wxApp,wxUser,userWxInfo);
                    wxUserService.save(wxUser);
                // 曾经关注过
                }else{
                    wxUser.setSubscribeNum(wxUser.getSubscribeNum()+1);
                    setWxUserValue(wxApp,wxUser,userWxInfo);
                    wxUserService.updateById(wxUser);
                }

                // 发送关注消息
                List<WxAutoReply> list = wxAutoReplyService.lambdaQuery()
                        .eq(WxAutoReply::getAppId, wxApp.getId())
                        .eq(WxAutoReply::getType, WxConstant.WX_AUTO_REPLY_TYPE_1)
                        .list();
                WxMpXmlOutMessage wxMpXmlOutMessage = MsgHandler.getWxMpXmlOutMessage(wxMessage, list, wxApp, wxUser, wxMsgService, null);
                return wxMpXmlOutMessage;
            }

        }
        return null;
    }

    public static void setWxUserValue(WxApp wxApp, WxUser wxUser, WxMpUser userWxInfo) {
        wxUser.setAppType(wxApp.getAppType());
        wxUser.setAppId(wxApp.getAppId());
        wxUser.setSubscribe(WxConstant.SUBSCRIBE_TYPE_YES);
        wxUser.setSubscribeScene(userWxInfo.getSubscribeScene());
        if(null != userWxInfo.getSubscribeTime()){
            wxUser.setSubscribeTime(LocalDateTimeUtils.timestamToDatetime(userWxInfo.getSubscribeTime()*1000));
        }
        wxUser.setOpenId(userWxInfo.getOpenId());
        wxUser.setNickName(userWxInfo.getNickname());
        wxUser.setLanguage(userWxInfo.getLanguage());
        wxUser.setRemark(userWxInfo.getRemark());
        wxUser.setHeadImgUrl(userWxInfo.getHeadImgUrl());
        wxUser.setUnionId(userWxInfo.getUnionId());
        wxUser.setGroupId(JSON.toJSONString(userWxInfo.getGroupId()));
        wxUser.setTagIdList(userWxInfo.getTagIds());
        wxUser.setQrSceneStr(userWxInfo.getQrSceneStr());
    }

}
